﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using WoBian.Lib.ConstString;
using WoBian.Common;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using WoBian.ServiceModel;
namespace WoBian.Models.Admin.Login
{
    public class ValidateCodeModel
    {
        public string ValidateCode
        {
            get { return MyApplicationContext.Current.ValidateCode; }
            set { MyApplicationContext.Current.ValidateCode = value; }
        }

        private string[] CodeChar = new string[] {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v"
        ,"w","x","y","z","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q"
        ,"R","S","T","U","V","W","X","Y","Z"};

        public byte[] Image { get; set; }

        /// <summary>
        /// 验证码长度
        /// </summary>
        private int CodeLength { get { return 5; } }

        public string CreateValidateCode()
        {
            string Code = string.Empty;
            Random r = new Random();
            for (int i = 0; i < CodeLength; i++)
            {
                Code += CodeChar[r.Next(CodeChar.Length - 1)];
            }
            return Code;
        }

        public byte[] CreateValidateCodeImage()
        {
            ValidateCode = CreateValidateCode();
            Bitmap bitmap = new Bitmap( Math.Ceiling(ValidateCode.Length * 12.0).ToInt32(), 25);
            Graphics g = Graphics.FromImage(bitmap);
            try
            {
                g.Clear(Color.White);
                Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bitmap.Width, bitmap.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(ValidateCode,font,brush,3,2);
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
                MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                bitmap.Dispose();
            }
        }
    }
}
